package com.wan37.logic.component;

/**
 * @author : luoyong
 * @date : 2020-05-28 09:47
 **/

import com.wan37.logic.handler.MsgHandler;
import com.wan37.logic.handler.WorkerHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

/**
 * 每一个Worker代表一个作业线程.
 * 每个worker有自己的阻塞队列.
 *
 * @author ly
 */
public class Worker implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(Worker.class);

    /**
     * 是否停止的标记
     */
    public volatile boolean stop = false;

    /**
     * 保存MsgHandler并排队的阻塞队列.
     * 每个worker作业线程都有一个阻塞队列.
     */
    private final BlockingQueue<WorkerHandler> WorkerHandlerQueue = new LinkedBlockingDeque<>();


    /**
     * 每个worker在单独的线程里跑自己的run方法.
     */
    @Override
    public void run() {

        while (!stop) {
            WorkerHandler workerHandler = null;
            try {
                //获取消息队列队头元素, 超时时间500ms
                workerHandler = WorkerHandlerQueue.poll(500, TimeUnit.MILLISECONDS);
                if (workerHandler == null) {
                    //如果workerHandler为null, 说明阻塞队列为空
                    continue;
                }
            } catch (InterruptedException e) {
                logger.error("[LogicServer] Worker中断异常！！！");
            }
            try {
                //执行WorkerHandler的execute方法, 处理消息.
                workerHandler.execute(this);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }


    /**
     * 向worker中的任务队列中添加一个WorkerHandler.
     *
     * @param workerHandler
     */
    public void addMsgHandler(WorkerHandler workerHandler) {

        if (workerHandler != null) {
            //添加一个msgHandler到任务队列(阻塞队列)中
            this.WorkerHandlerQueue.offer(workerHandler);
        }
    }

}
